package com.sojson.config.filter;

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.sojson.config.filter.interfaces.ResponseBodyFilterInterface;
import com.sojson.result.interfaces.BeforeBodyWriteInterface;
import com.sojson.util.filter.FilterUtil;
import com.sojson.util.servlet.ServletUtil;

/**
 * 将返回的对象转为Json字符串过滤器
 * 
 * @author liu
 * @date 2020-10-06
 */
public class ResponseBodyJsonFilter implements ResponseBodyFilterInterface {

    /** 不过滤的路径 */
    private HashSet<String> excludePath;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        if (isExcludePath(excludePath)) {
            chain.doFilter(request, response);
            return;
        }

        setValRequest(BeforeBodyWriteInterface.RESPONSE_BODY_TYPE_KEY,
            BeforeBodyWriteInterface.JSON_STRING);

        chain.doFilter(request, response);
    }

    /**
     * 判断当前路径是否不过滤(过滤器无法设置不过滤哪些路径,要自己做)
     * 
     * @return
     */
    private boolean isExcludePath(HashSet<String> excludePath) {
        return FilterUtil.isExcludePath(excludePath);
    }

    /**
     * 把值放入到当前的Request里
     * 
     * @param key
     * @param value
     */
    private void setValRequest(String key, Object value) {
        ServletUtil.setValRequest(key, value);
    }

    /**
     * 获取不过滤的路径
     * 
     * @return
     */
    @Override
    public HashSet<String> getExcludePath() {
        return this.excludePath;
    }

    /**
     * 设置不过滤的路径
     * 
     * @param excludePath
     */
    @Override
    public void setExcludePath(HashSet<String> excludePath) {
        this.excludePath = excludePath;
    }

    /**
     * 获取当前过滤器的名字
     */
    @Override
    public String getName() {
        String name = "resuStr";
        return name;
    }

}